package com.derekandbritt.booST;

import java.util.Date;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.derekandbritt.booST.data.Challenge;
import com.derekandbritt.booST.exceptions.ConnectionException;
import com.derekandbritt.booST.exceptions.DataFormatException;
import com.derekandbritt.booST.exceptions.GenericException;

public class ViewChallenge extends booSTActivity {

	public final static String CHALLENGE_KEY = "com.derekandbritt.booST.challenge";

	private Challenge challenge;
	
	public void displayContent() throws ConnectionException, DataFormatException {
		
		this.setContentView(R.layout.challenge);
    	
		long challengeId = this.getIntent().getExtras().getLong(CHALLENGE_KEY);
		challenge = booSTEndpoint.getChallenge(challengeId);
		
		displayChallenge();
	}

	public void handleResume() throws ConnectionException, DataFormatException {
		//refresh the challenge
		displayContent();
	}
	
	private void displayChallenge() throws ConnectionException, DataFormatException {
		
	    String userId = booSTEndpoint.getUser().userID;;
	    
		String friendId;
    	if(challenge.getSender().equals(userId))
    		friendId = challenge.getReceiver();
    	else
    		friendId = challenge.getSender();
		
		configurePersonalStatus();
		configureFriendsStatus(friendId);
		configureChallengeDetails(challenge, friendId);
		configureChallengeState(challenge, friendId);
		
	}
	
	private void configureChallengeState(Challenge challenge, String challengerId) {
		
		TextView statusText = (TextView)findViewById(R.id.ChallengeStatus);
		
		LinearLayout parentView = (LinearLayout)findViewById(R.id.ChallengeStatusUI);
		parentView.removeAllViews();
		
		Challenge.Status status = challenge.getStatus();
		boolean isSender = challenge.getReceiver().equals(challengerId);
		boolean isCompleted = (isSender && challenge.getSenderTime() != 0) || (!isSender && challenge.getReceiverTime() != 0);
		
		//if pending and you sent it then you can do nothing
		if(Challenge.Status.PENDING == status && isSender) {
			statusText.setText("Sent");
			//statusText.setTextColor(this.getResources().getColorStateList(R.color.energy_positive));
			parentView.addView(View.inflate(this, R.layout.challenge_sent, null));
		}
		//if pending and you received it then you can accept or reject
		else if(Challenge.Status.PENDING == status && !isSender) {
			statusText.setText("Pending");
			parentView.addView(View.inflate(this, R.layout.challenge_received, null));
			setupPendingButtons();
		}
		//if accepted and you have not completed
		else if(Challenge.Status.ACCEPTED == status && !isCompleted) {
			statusText.setText("Active");
			parentView.addView(View.inflate(this, R.layout.challenge_active, null));
			setupActiveButtons();
		}
		//if accepted and you have completed
		else if(Challenge.Status.ACCEPTED == status && isCompleted) {
			statusText.setText("Completed");
			parentView.addView(View.inflate(this, R.layout.challenge_waiting, null));
			setupIndividualResults(isSender, true);
		}
		//if completed
		else if(Challenge.Status.COMPLETED == status) {
			statusText.setText("Completed");
			parentView.addView(View.inflate(this, R.layout.challenge_completed, null));
			setupFinalResults(isSender);
		}
		//if rejected
		else if(Challenge.Status.REJECTED == status) {
			statusText.setText("Rejected");
			parentView.addView(View.inflate(this, R.layout.challenge_rejected, null));
		}
	    //if expired
        else if(Challenge.Status.EXPIRED == status) {
            statusText.setText("Expired");
            parentView.addView(View.inflate(this, R.layout.challenge_expired, null));
        }
	}
	
	private void setupPendingButtons() {
    	
    	Button accept = (Button)this.findViewById(R.id.ChallengeAcceptButton);
    	accept.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {
				challenge.setStatus(Challenge.Status.ACCEPTED);
				challenge.setLastUpdated(new Date(System.currentTimeMillis()));
				try {
					setChallenge(challenge);
					displayChallenge();
				} catch (GenericException e) {
					handleError(e);
				}
			}
		});
    	
    	Button reject = (Button)this.findViewById(R.id.ChallengeRejectButton);
    	reject.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {
				challenge.setStatus(Challenge.Status.REJECTED);
				challenge.setLastUpdated(new Date(System.currentTimeMillis()));
				try {					
					booSTEndpoint.setChallenge(challenge);
					displayChallenge();
				} catch (GenericException e) {
					handleError(e);
				}
			}
		});
	}
	
	private void setupActiveButtons() {
    	
    	Button start = (Button)this.findViewById(R.id.ChallengeStartButton);
    	start.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {
				// fire an intent to start the racing interface...
				Intent intent = new Intent();
				intent.setClassName("com.derekandbritt.booST", "com.derekandbritt.booST.ActiveChallenge");
				intent.putExtra(ActiveChallenge.CHALLENGE_KEY, challenge.getId());
				view.getContext().startActivity(intent);
			}
		});
	}
	
	private void setupFinalResults(boolean isSender) {
		
		setupIndividualResults(isSender, true);   // setup your results
		setupIndividualResults(!isSender, false); // setup challenger's results
		
		int senderTime = challenge.getSenderTime();
		int receiverTime = challenge.getReceiverTime();
		
		// put the winner/loser declaration here!
		if(Challenge.Type.COOPERATIVE == challenge.getType()) {
			int maxTime = challenge.getTimeLimit()*60000;
			if(senderTime <= maxTime && receiverTime <= maxTime && senderTime != -1 && receiverTime != -1)
				this.findViewById(R.id.ChallengeWinnerText).setVisibility(View.VISIBLE);
			else
				this.findViewById(R.id.ChallengeLoserText).setVisibility(View.VISIBLE);
		}
		else {
			if((isSender && senderTime <= receiverTime) || (!isSender && receiverTime <= senderTime))
				this.findViewById(R.id.ChallengeWinnerText).setVisibility(View.VISIBLE);
			else
				this.findViewById(R.id.ChallengeLoserText).setVisibility(View.VISIBLE);
		}
	}
	
	private void setupIndividualResults(boolean isSender, boolean isSelf) {

		int time = (isSender ? challenge.getSenderTime() : challenge.getReceiverTime());
		
		TextView passView = (TextView)(isSelf ? findViewById(R.id.ChallengePassSelf) : findViewById(R.id.ChallengePassOther));
		TextView failView = (TextView)(isSelf ? findViewById(R.id.ChallengeFailSelf) : findViewById(R.id.ChallengeFailOther));
		TextView quitView = (TextView)(isSelf ? findViewById(R.id.ChallengeQuitSelf) : findViewById(R.id.ChallengeQuitOther));
		TextView timeView = (TextView)(isSelf ? findViewById(R.id.ChallengeTimeSelf) : findViewById(R.id.ChallengeTimeOther));
		
		if(time == -1) {
			quitView.setVisibility(View.VISIBLE);
		}
		else if(Challenge.Type.COOPERATIVE == challenge.getType()) {
			if((challenge.getTimeLimit()*60000) > time) {
				passView.setVisibility(View.VISIBLE);
				timeView.setVisibility(View.VISIBLE);
				timeView.setText("(" + formatTime((challenge.getTimeLimit()*60000) - time) + " remaining)");
			} else
				failView.setVisibility(View.VISIBLE);
		}
		else if(Challenge.Type.COMPETITIVE == challenge.getType()) {
			timeView.setVisibility(View.VISIBLE);
			timeView.setText(formatTime(time) + " total time");
		}
	}
	
	private String formatTime(int milliseconds) {
		long minutes = milliseconds / 60000;
		long seconds = (milliseconds % 60000) / 1000;
		
		String minutesText = (minutes < 10 ? "0" + minutes  : "" + minutes);
		String secondsText = (seconds < 10 ? "0" + seconds  : "" + seconds);
		
		return minutesText + ":" + secondsText;
	}
}
